package com.dungnt.vtime.stopwatch;

import android.app.Fragment;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.dungnt.vtime.R;
import com.dungnt.vtime.utils.Utils;

public class VTStopWatchFragment extends Fragment implements OnClickListener {
	private View v;
	private Button btnStart, btnStop, btnReset, btnLapTime;
	private TextView tvTime;
	private Handler mHandler = new Handler();
	private long startTime;
	private long elapsedTime;
	private String hours, minutes, seconds, milliseconds;
	private long secs, mins, hrs, msecs;
	private boolean stopped = false;
	private final int REFRESH_RATE = 1;
	private Runnable startTimer = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			elapsedTime = System.currentTimeMillis() - startTime;
			String time = Utils.updateTimer(elapsedTime,true);
			tvTime.setText(time);
			mHandler.postDelayed(this, REFRESH_RATE);
		}
	};

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		v = inflater.inflate(R.layout.stopwatch_fragment, container, false);
		return v;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		btnStart = (Button) v.findViewById(R.id.btnStart);
		btnStop = (Button) v.findViewById(R.id.btnStop);
		btnReset = (Button) v.findViewById(R.id.btnReset);
		tvTime = (TextView) v.findViewById(R.id.tvTimeST);
		btnLapTime = (Button) v.findViewById(R.id.btnLapTime);
		btnStart.setOnClickListener(this);
		btnStop.setOnClickListener(this);
		btnReset.setOnClickListener(this);
		btnLapTime.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v == btnStart) {
			if (stopped) {
				startTime = System.currentTimeMillis() - elapsedTime;
			} else
				startTime = System.currentTimeMillis();
			mHandler.removeCallbacks(startTimer);
			mHandler.postDelayed(startTimer, 0);
		} else if (v == btnStop) {
			mHandler.removeCallbacks(startTimer);
			stopped = true;
		} else if (v == btnReset) {
			stopped = false;
			mHandler.removeCallbacks(startTimer);
			tvTime.setText("00:00:00.000");
		} else if (v == btnLapTime) {
			Log.d("DungNT", lapTime().toString());
		}
	}

	private LapTimeItem lapTime() {
		LapTimeItem lapItem = new LapTimeItem(hrs, mins, secs, msecs);
		return lapItem;
	}

}
